package com.chenyuxin.ilp.security.perm.refresh;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWTUtil;
import com.chenyuxin.ilp.model.constant.ExpireTimeConstant;
import com.chenyuxin.ilp.model.constant.UserSuccessConstant;
import com.chenyuxin.ilp.model.enums.exception.UserExceptionEnums;
import com.chenyuxin.ilp.model.pojo.Result;
import com.chenyuxin.ilp.model.vo.user.UserLoginVo;
import com.chenyuxin.ilp.security.perm.handler.RefreshException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.*;

public class RefreshTokenAuthenticationFilter extends OncePerRequestFilter {
    private String jwtKey = "12345678";
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String refreshToken = request.getHeader("Refresh-Token");
        boolean verify;
        try{
            verify = JWTUtil.verify(refreshToken, jwtKey.getBytes());
        }catch (Exception e){
            throw new RefreshException(UserExceptionEnums.REFRESH_TOKEN_ERROR);
        }
        if(refreshToken==null|| !verify){
            throw new RefreshException(UserExceptionEnums.REFRESH_TOKEN_ERROR);
        }
        JSONObject payloads = JWTUtil.parseToken(refreshToken).getPayloads();
        if(!(((Number)payloads.get("exp")).longValue()>System.currentTimeMillis())){
            throw new RefreshException(UserExceptionEnums.REFRESH_TOKEN_EXPIRE);
        }
        UserLoginVo userLoginVo = BeanUtil.toBean(payloads, UserLoginVo.class);
        Map<String,String> tokenMap = this.refresh(userLoginVo);
        response.setHeader("Authorization",tokenMap.get("token"));
        response.setHeader("Refresh-Token",tokenMap.get("refreshToken"));
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(JSONUtil.toJsonStr(Result.ok(UserSuccessConstant.REFRESH_TOKEN_SUCCESS,null)));
    }
    private Map<String,String> refresh(UserLoginVo userLoginVo){
        Map<String, Object> map = BeanUtil.beanToMap(userLoginVo);
        map.put("exp",System.currentTimeMillis() + ExpireTimeConstant.TOKEN_EXPIRE_TIME);
        String token = "Bearer " + JWTUtil.createToken(map, jwtKey.getBytes());
        map.put("exp",System.currentTimeMillis() + ExpireTimeConstant.REFRESH_TOKEN_EXPIRE_TIME);
        String refreshToken = JWTUtil.createToken(map, jwtKey.getBytes());
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token",token);
        tokenMap.put("refreshToken",refreshToken);
        return tokenMap;
    }
}
